package com.detrum.sportcamera.nfstask;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.detrum.NFSVideo;
import com.detrum.bean.FileBean;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.utils.LogUtils;
import com.detrum.utils.NfsUtil;

import java.util.ArrayList;

/**
 * Created by abc on 2018/1/2.
 */

public class NfsGetFiles extends AsyncTask<String, FileBean, String> {
    private final String TAG = "NfsGetFiles";
    private Context context;
    private int index;
    private ArrayList<FileBean> dataList = new ArrayList<>();
    private ArrayList<String> folderList = new ArrayList<>();
    private ArrayList<String> folderList2 = new ArrayList<>();
    private GetFilesCall getFilesCall;
    private int position;
    private boolean isStop;

    public NfsGetFiles(int index, Context context, GetFilesCall getFilesCall) {
        this.index = index;
        this.context = context;
        this.getFilesCall = getFilesCall;
    }

    public void Stop() {
        isStop = true;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        LogUtils.e("getNfsFileCall finish");
        getFilesCall.finish();
    }

    @Override
    protected void onProgressUpdate(FileBean... values) {
        super.onProgressUpdate(values);
        getFilesCall.sendList(values[0]);
    }

    @Override
    protected String doInBackground(String... paths) {
        dataList.clear();
        if(paths==null){
            getFiles("/");
        }else{
            getFiles(paths[0]);
        }
        while (true) {
            if (isStop) {
                break;
            }
            if (folderList != null && folderList.size() != 0) {
                int size = folderList.size();
                for (int i = 0; i < size; i++) {
                    getFiles2(folderList.get(i));
                }
                folderList.clear();
            }
            if (folderList2 != null && folderList2.size() != 0) {
                int size2 = folderList2.size();
                for (int i = 0; i < size2; i++) {
                    getFiles(folderList2.get(i));
                }
                folderList2.clear();
            }
            if (folderList!=null&&folderList2!=null&&folderList.size() == 0 && folderList2.size() == 0) {
                break;
            }
        }
        return "finish";
    }

    private ArrayList<FileBean> getFiles(String folder) {
        LogUtils.i("opendir folder is " + folder);
        int dir;
        if (folder.startsWith("/")) {
            LogUtils.i("getFiles folder = "+folder);
            dir = NFSVideo.opendir(folder, index);
        } else {
            LogUtils.i("getFiles / = "+"/" + folder);
            dir = NFSVideo.opendir("/" + folder, index);
        }
        LogUtils.i("getFiles dir = "+dir);
        if(dir<0){
            getFilesCall.fail();
            return null;
        }
        byte[] filemode = new byte[11];
        long[] mtime = new long[1];
        long[] filesize = new long[1];
        int name_len = 0;
        while (true) {
            byte[] filename = new byte[1024];
            int flag = NFSVideo.readdir(filename, filemode, mtime, filesize, index);
            if (flag < 0) {
                break;
            }
            name_len = 0;

            for (int i = 0; i < filename.length; i++) {
                if (filename[i] == 0) {
                    break;
                }
                name_len++;
            }

            FileBean bean = new FileBean();
            String name = new String(filename, 0, name_len);
            String mode = new String(filemode, 0, 1);
            long time = mtime[0];
            if (!TextUtils.isEmpty(folder)) {
                if (folder.startsWith("/")) {
                    name = folder + "/" + name;
                } else {
                    name = "/" + folder + "/" + name;
                }
            }
            if (NfsUtil.isNFSFile(name)) {         //筛选文件
                //初次获取文件只保存Nfs路径，文件名，时间，大小
                bean.setNfsPath(name);
                bean.setFileName(NfsUtil.splitName(name));
                bean.setSize(filesize[0]);
                bean.setFileTime(time);
                bean.setIsNfs(1);
                String nfsName = SqliteMediaOperation.getInstence(context).getNfsPath(NfsUtil.splitName(name));
                if (nfsName != null) {
                    int update = SqliteMediaOperation.getInstence(context).UpdataItemNfs(bean,  NfsUtil.splitName(name));
                   // LogUtils.i("NfsGetFiles update = "+update+"   nfsName = "+name);
                } else {
                    long insert = SqliteMediaOperation.getInstence(context).Insert(bean);
                   // LogUtils.i("NfsGetFiles insert = "+insert+"   nfsName = "+name);
                }
                publishProgress(bean);
                position++;
            }
            if (NfsUtil.isFolder(mode, name)) {
                folderList.add(name);
            }
        }
        NFSVideo.closedir(index);
        return dataList;
    }

    private ArrayList<FileBean> getFiles2(String folder) {
        LogUtils.e("opendir folder is " + folder);
        NFSVideo.opendir("/" + folder, index);
        byte[] filemode = new byte[11];
        long[] mtime = new long[1];
        long[] filesize = new long[1];
        int name_len = 0;
        while (true) {
            byte[] filename = new byte[1024];
            int flag = NFSVideo.readdir(filename, filemode, mtime, filesize, index);
            if (flag < 0) {
                break;
            }
            name_len = 0;

            for (int i = 0; i < filename.length; i++) {
                if (filename[i] == 0) {
                    break;
                }
                name_len++;
            }

            FileBean bean = new FileBean();
            String name = new String(filename, 0, name_len);
            String mode = new String(filemode, 0, 1);
            long time = mtime[0];
            if (!TextUtils.isEmpty(folder)) {
                if (folder.startsWith("/")) {
                    name = folder + "/" + name;
                } else {
                    name = "/" + folder + "/" + name;
                }
            }
            if (NfsUtil.isNFSFile(name)) {         //筛选文件
                //初次获取文件只保存Nfs路径，文件名，时间，大小
                bean.setNfsPath(name);
                bean.setFileName(NfsUtil.splitName(name));
                bean.setSize(filesize[0]);
                bean.setFileTime(time);
                bean.setIsNfs(1);
                String nfsName = SqliteMediaOperation.getInstence(context).getNfsPath(NfsUtil.splitName(name));
                // LogUtils.e(TAG,"getFiles2 ret = "+ret+"\nfileName is "+NfsUtil.splitName(name));
                if (nfsName != null) {
                    int update = SqliteMediaOperation.getInstence(context).UpdataItemNfs(bean, NfsUtil.splitName(name));
                   // LogUtils.i("NfsGetFiles update = "+update+"   nfsName = "+name);
                } else {
                    long insert = SqliteMediaOperation.getInstence(context).Insert(bean);
                   // LogUtils.i("NfsGetFiles insert = "+insert+"   nfsName = "+name);
                }
                if(dataList!=null){
                    dataList.add(bean);
                }
                position++;
                // LogUtils.e(TAG,"dataList size = "+dataList.size());
                if (dataList != null) {
                    if (dataList.size() < 10) {
                        dataList.add(bean);
                    } else {
                        FileBean[] beans = new FileBean[dataList.size()];
                        dataList.toArray(beans);
                        publishProgress(beans);
                        dataList.clear();
                        dataList = null;
                    }
                }
            }
            if (NfsUtil.isFolder(mode, name)) {
                folderList2.add(name);
            }
        }
        NFSVideo.closedir(index);
        return dataList;
    }

}
